package examples;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;

public class Webpagetest extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
		
		//Goto homepage
		String url = "http://www.webpagetest.org/";
		Connection conn = Jsoup.connect(url);
		Document doc = conn
						.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
						.header("accept-Language", "en-us,en;q=0.5")
						.header("referer", "http://www.webpagetest.org/")
						.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1")
						.get();
		Response response = conn.response();
		String vh = doc.select("input[name=vh]").get(0).attr("value");
		String vo = doc.select("input[name=vo]").get(0).attr("value");
		String vd = doc.select("input[name=vd]").get(0).attr("value");
		
		try {
			Thread.sleep(5000);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		url = "http://www.webpagetest.org/runtest.php";
		conn = Jsoup.connect(url);
		
		//Goto runtest.php
		 doc = conn
						.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
						.header("accept-Language", "en-us,en;q=0.5")
						.header("host", "www.webpagetest.org")
						.header("referer", "http://www.webpagetest.org/")
						.cookie("o",response.cookie("o"))
						.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1")
						.data("url", "1stapp.org")
						.data("vh",vh)
						.data("vo", vo)
						.data("vd", vd)
						.data("where", "Dulles_VA")
						.data("browser", "IE8")
						.data("location", "Dulles_IE8.DSL")
						.data("bwDown", "1500")
						.data("bwUp", "384")
						.data("latency", "")
						.followRedirects(false)
						.post();
		
		try {
			Thread.sleep(5000);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		 response = conn.response();
		
	    System.out.println(response.headers());
	    System.out.println(response.header("server"));
	    System.out.println(response.header("Location"));
	    
	    
	    System.out.println(response.contentType());
	    
	    System.out.println(doc.outputSettings().charset());
	    //System.out.println(doc.outerHtml());
	    resp.getWriter().write(response.body());
	    resp.getWriter().flush();
	
	}
}
